package middleware

import (
	"github.com/gin-gonic/gin"
	"time"
	"todo-list/utils/loggers"
)

func LogMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// Start timer
		start := time.Now()
		path := ctx.Request.URL.Path
		raw := ctx.Request.URL.RawQuery

		// Process request
		ctx.Next()

		// Log only when path is not being skipped
		end := time.Now()
		latency := float64(end.Sub(start)) / 100000

		clientIP := ctx.ClientIP()
		method := ctx.Request.Method
		statusCode := ctx.Writer.Status()
		errorMessage := ctx.Errors.ByType(gin.ErrorTypePrivate).String()

		//bodySize := ctx.Writer.Size()

		if raw != "" {
			path = path + "?" + raw
		}
		// 设置颜色
		loggers.GinLogInfo(start, statusCode, latency, clientIP, method, path, errorMessage)
	}
}
